package com.inwavetech.os;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.inwavetech.os.entity.Os;
import com.inwavetech.os.entity.User;
import com.inwavetech.os.sync.SyncAdapter;
import com.inwavetech.os.util.DaoHelper;
import com.inwavetech.os.util.OsWidgetPlotter;
import com.inwavetech.os.util.SessionManager;
import com.inwavetech.os.util.SyncUtils;

import java.sql.SQLException;
import java.util.List;

public class MainActivity extends BaseOsCheckActivity {

    private SessionManager sessionManager;
    private LinearLayout mainContainer;
    private OsWidgetPlotter osWidgetPlotter;
    private SyncUtils syncUtils;
    private User loggedInUser;
    private SyncBroadcastReceiver syncReceiver = new SyncBroadcastReceiver();

    private final static int SYNC_STATUS_IDLE = 0;
    private final static int SYNC_STATUS_REQUESTED = 1;
    private final static int SYNC_STATUS_SYNCYING = 2;
    private int syncStatus = SYNC_STATUS_IDLE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DaoHelper daoHelper = getHelper();
        sessionManager = new SessionManager(this, daoHelper);
        syncUtils = new SyncUtils(this);

        // check the user login and redirect if it is not valid
        getUser();
    }

    @Override
    protected void onResume() {
        super.onResume();

        // check the user login status. WARNING: it can redirect the user
        loggedInUser = getUser();
        if (loggedInUser == null) {
            return;
        }

        plotOs();

        registerReceiver(syncReceiver, new IntentFilter(SyncAdapter.SYNC_STATUS_ACTION));
    }

    @Override
    protected void onPause() {
        super.onPause();

        unregisterReceiver(syncReceiver);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_logout) {
            sessionManager.logoutUser();
        } else if(id == R.id.action_sync) {
            sync();
        }

        return super.onOptionsItemSelected(item);
    }

    private void plotOs() {
        // reset the widget plotter and the screen widgets
        getOsWidgetPlotter().clear();

        // show the current stored oses
        try {
            List<Os> oses = getOsDao().queryBuilder()
                    .orderBy("activated_date", false)
                    .where()
                    .eq("user_id", loggedInUser.username)
                    .query();
            getOsWidgetPlotter().plotOses(oses);
        } catch (SQLException e) {}
    }

    private void sync() {
        switch (syncStatus) {
            case SYNC_STATUS_IDLE:
                syncStatus = SYNC_STATUS_REQUESTED;
                Toast.makeText(getApplicationContext(), getString(R.string.main_sync_request), Toast.LENGTH_LONG).show();
                syncUtils.syncNow();
                break;

            case SYNC_STATUS_REQUESTED:
                Toast.makeText(getApplicationContext(), getString(R.string.main_sync_waiting), Toast.LENGTH_LONG).show();
                break;

            case SYNC_STATUS_SYNCYING:
                Toast.makeText(getApplicationContext(), getString(R.string.main_sync_proccessing), Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private OsWidgetPlotter getOsWidgetPlotter() {
        if (osWidgetPlotter == null) {
            osWidgetPlotter = new OsWidgetPlotter(this, getHelper(), getMainContainer());
        }

        return osWidgetPlotter;
    }

    private ViewGroup getMainContainer() {
        if (mainContainer == null) {
            mainContainer = (LinearLayout) findViewById(R.id.container);
        }

        return mainContainer;
    }

    class SyncBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String feedbackMsg;
            int broadcastStatus = intent.getIntExtra(SyncAdapter.SYNC_STATUS_KEY, SyncAdapter.SYNC_STATUS_FAIL);

            switch (broadcastStatus) {
                case SyncAdapter.SYNC_STATUS_PROCCESS:
                    feedbackMsg = getString(R.string.main_sync_proccessing);
                    syncStatus = SYNC_STATUS_SYNCYING;
                    break;

                case SyncAdapter.SYNC_STATUS_SUCCESS:
                    feedbackMsg = getString(R.string.main_sync_success);
                    plotOs();
                    syncStatus = SYNC_STATUS_IDLE;
                    break;

                default: // SyncAdapter.SYNC_STATUS_FAIL or any unknown status
                    feedbackMsg = getString(R.string.main_sync_fail);
                    syncStatus = SYNC_STATUS_IDLE;
                    break;
            }

            Toast.makeText(getApplicationContext(), feedbackMsg, Toast.LENGTH_LONG).show();
        }
    }
}
